<template>
  <!-- 添加和修改课时表单 -->
  <el-dialog :visible.sync="dialogVisible" title="添加课时" @close="close()">
    <el-form :model="period" label-width="120px">
      <el-form-item label="课时标题">
        <el-input v-model="period.periodName"/>
      </el-form-item>
      <el-form-item label="课时排序">
        <el-input-number v-model="period.sort" :min="0" controls-position="right"/>
      </el-form-item>
      <el-form-item label="是否免费">
        <el-radio-group v-model="period.free">
          <el-radio-button :label="1">免费</el-radio-button>
          <el-radio-button :label="0">默认</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="课时类型">
        <el-radio-group v-model="periodCategory">
          <el-radio-button :label="0">视频</el-radio-button>
          <el-radio-button :label="1">文档</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item  v-if="periodCategory === 0" label="上传视频">
        <el-upload
          :on-success="handleVodUploadSuccess"
          :on-exceed="handleUploadExceed"
          :on-remove="handleVodRemove"
          :before-remove="beforeVodRemove"
          :file-list="vodList"
          accept=".3gp,.asf,.avi,.flv,.mpeg.,ogg,.mp4,.swf,.wmv,.webm"
          :action="BASE_API+'/teacher/vod/video/upload'"
          :limit="1"
          class="upload-demo">
          <el-button size="medium" type="primary">上传视频</el-button>
            <div slot="tip" class="el-upload__tip">文件大小最大支持1G，<br>
              支持3GP、ASF、AVI、DAT、DV、FLV、F4V、
              GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
              MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、
              SWF、TS、VOB、WMV、WEBM 等视频格式上传</div>
        </el-upload>
      </el-form-item>

      <el-form-item  v-if="periodCategory === 1" label="上传文档">
        <el-upload
          :on-success="handleFileUploadSuccess"
          :on-exceed="handleUploadExceed"
          :on-remove="handleFileRemove"
          :before-remove="beforeVodRemove"
          :file-list="fileList"
          accept=".zip,.rar,.7z,.tar"
          :action="BASE_API+'/teacher/oss/file/upload?host=course&courseId='+period.courseId"
          :limit="1"
          class="upload-demo">
          <el-button size="medium" type="primary">上传文档</el-button>
          <div slot="tip" class="el-upload__tip">文件大小最大支持1G，<br>
            支持ZIP、RAR、TAR、7Z等压缩文件格式上传</div>
        </el-upload>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { savePeriod,getPeriodById,updatePeriodById } from '@/api/period'
  import { deleteVideoById } from '@/api/vod'
  import { deleteOssFileByUrl } from '@/api/oss'

  export default {

    // 父组件向子组件传值
    props: {
      courseId: {
        type: String,
        default: null
      }
    },

    watch: {
      periodCategory:{
        handler: function(val, oldVal) {
          this.$message({
            type: 'info',
            message: '如果本课时存在视频或文档资源，切换课时类型会导致文件删除，需重新上传'
          })
          // 重置表单
          // this.resetForm()
          // 课时类型为视频
          if (val === 0){
            this.period.video = 1
            this.period.doc = 0
            this.period.docName = ''
            this.period.docUrl = ''
          }
          // 课时类型为文档
          if (val === 1){
            this.period.doc = 1
            this.period.video = 0
            this.period.videoId = ''
            this.period.videoName = ''
          }
        }
      }
    },
    data() {
      return {
        //课时类型 0视频 1文档
        periodCategory: 0,
        dialogVisible: false,
        period: {
          periodId: '',
          courseId: '',
          chapterId: '',
          periodName: '',
          videoName: '',
          sort: 0,
          free: 0,
        },
        vodList: [],  // 上传视频列表
        fileList: [], // 上传文档列表
        BASE_API: process.env.VUE_APP_BASE_API, // 接口API地址
        OSS_URL: 'http://czz-education.oss-cn-shenzhen.aliyuncs.com/' //阿里云oss地址

        //上传视频参数
        timeout: '',
        partSize: '',
        parallel: '',
        retryCount: '',
        retryDuration: '',
        region: 'cn-shanghai',
        userId: '1634605963684131',
        file: null,
        authProgress: null,
        uploadDisabled: true,
        uploader: null,
        statusText: ''
      }
    },

    methods: {
      open(chapterId, periodId) {
        this.dialogVisible = true
        this.period.chapterId = chapterId
        this.period.courseId = this.courseId
        if (periodId){
          getPeriodById(periodId).then(result => {
            this.period = result.data.item
            delete this.period.gmtCreate
            delete this.period.gmtModified

            if (this.period.video === 1) this.periodCategory = 0
            if (this.period.doc === 1) this.periodCategory = 1

            if (this.period.videoId && this.period.videoName) {
              this.vodList = [{ 'name': this.period.videoName }]
            }

            if (this.period.docUrl && this.period.docName){
              this.fileList = [{ 'name': this.period.docName }]
            }
          })
        }
      },

      close() {
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },

      resetForm() {
        this.period.periodName = ''
        this.period.sort = 0
        this.period.chapterId = ''
        this.period.periodId = ''
        this.period.courseId = ''
        this.period.free = 0
        this.period.videoId = ''
        this.period.videoName = ''
        this.fileList = []
        this.vodList = []
      },

      saveOrUpdate() {
        if (!this.period.periodId) {
          this.save()
        } else {
          this.update()
        }
      },

      save() {
        this.period.courseId = this.courseId
        savePeriod(this.$qs.stringify(this.period)).then(result => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          // 关闭组件
          this.close()
          // 调用父组件监听函数
          this.$emit('onSaveSuccess')
        })
      },

      update() {
        updatePeriodById(this.period.periodId, this.$qs.stringify(this.period)).then(result => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          // 关闭组件
          this.close()
          // 调用父组件监听函数
          this.$emit('onSaveSuccess')
        })
      },

      // 视频上传成功回调
      handleVodUploadSuccess(result, file){
        this.period.videoId = result.data.videoId
        this.period.videoName = file.name
      },


      // 上传多个文档/视频
      handleUploadExceed(){
        this.$message.warning('想要重新上传文件，请先删除已上传的文件')
      },

      // 文档/视频删除前回调
      beforeVodRemove(file) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },

      // 视频确定删除回调
      handleVodRemove(file, fileList) {
        deleteVideoById(this.period.videoId).then(result=>{
          this.period.videoId = ''
          this.period.videoName = ''
          this.update(this.period) // 更新video信息
          this.$message({
            type: 'success',
            message: result.message
          })
        })
      },

      // 文档成功上传回调
      handleFileUploadSuccess(result){
        this.period.docName = result.data.item.fileName
        this.period.docUrl = result.data.item.url
      },

      // 文档确定删除回调
      handleFileRemove(file, fileList){
        const url = this.period.docUrl.replace(this.OSS_URL,'').replace(/\//g, '&&')
        deleteOssFileByUrl(url).then(result=>{
          this.period.docName = ''
          this.period.docUrl = ''
          this.update(this.period) // 更新video信息
          this.$message({
            type: 'success',
            message: result.message
          })
        })
      }
    }
  }
</script>

<style scoped>

</style>
